package cn.bdqn.sys.service.impl;

import cn.bdqn.model.EUAttribute;
import cn.bdqn.model.EUNode;
import cn.bdqn.model.R;
import cn.bdqn.service.BaseService;
import cn.bdqn.sys.model.Resources;
import cn.bdqn.sys.model.User;
import cn.bdqn.sys.service.ResourcesService;
import cn.bdqn.sys.vomapper.ResourcesVoMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Awacky
 * @create 2019-07-27 17:41
 */
@Service
public class ResourcesServiceImpl extends BaseService implements ResourcesService {
    @Resource
    private ResourcesVoMapper resourcesVoMapper;


    @Override
    public R getMenu() {
        try {
            User user =this.getUser();
            List<Resources> menu = resourcesVoMapper.getMenu(user.getUid());
//        昨天晚上没想通，下面该怎么做，不知道从哪需要
//        创建一个eunode
            List<EUNode> nodes = new ArrayList<>();
            crateMenu(menu,nodes,-1);
            return R.ok(null,nodes);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("数据错误");
        }
    }

    //    这是一个递归式的动态创建树形
    //必须要有父节点
    private void crateMenu(List<Resources> ress, List<EUNode> menus, Integer id) {
        for (Resources res : ress) {
            if (res.getPid () == id) {
                EUNode node = new EUNode ();
                node.setId (res.getId ());
                node.setText (res.getCname ());
                node.setIconCls (res.getIcon ());
                node.setChecked (res.getIsdel ());
                if (res.getIsleaf ()) {
                    node.setStatus ("open");
                    node.setAttributes (new EUAttribute(res.getUrl ()));
//                    url可以点击
                } else {
                    List<EUNode> children = new ArrayList<>();
                    crateMenu (ress, children, res.getId ());
                    node.setChildren (children);
                }
                menus.add (node);
            }
        }
    }

    @Override
    public R getRes(Integer roleid) {
        try {
            List<Resources> menu = resourcesVoMapper.getRes(roleid);
//        昨天晚上没想通，下面该怎么做，不知道从哪需要
//        创建一个eunode
            List<EUNode> nodes = new ArrayList<>();
            crateMenu(menu,nodes,-1);
            return R.ok(null,nodes);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("数据错误");
        }
    }

}
